/*
This module contains all code that's not specific to the assignment at hand.
*/

// calling this function will exit the process upon pressing any key
// allowing for easy iterative testing
exports.exitOnKeyPress = function () {
    var stdin = process.stdin;
    // rawMode: don't wait for end-of-line
    stdin.setRawMode(true);
    // resume stdin in the parent process
    stdin.resume();
    stdin.on('data', process.exit);
}

// HTTP POST handling
var http = require('http'), querystring = require('querystring');
exports.processPost = function(request, response, callback) {
    var queryData = "";
    if (typeof callback !== 'function') return null;

    if (request.method == 'POST') {
        request.on('data', function (data) {
            queryData += data;
            if (queryData.length > 1e6) {
                queryData = "";
                response.writeHead(413, { 'Content-Type': 'text/plain' }).end();
                request.connection.destroy();
            }
        });

        request.on('end', function () {
            request.post = querystring.parse(queryData);
            callback();
        });

    } else {
        response.writeHead(405, { 'Content-Type': 'text/plain' });
        response.end();
    }
}